package com.qf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 *
 * 内部转发及重定向
 * @author lixu
 */
@Controller
public class ForwardController {


    /**
     * 重定向  携带参数
     */
    @GetMapping("/redirect")
    public String redirectTest1(Integer id, String name, RedirectAttributes redirectAttributes){
        System.out.println("redirect===:" + id);
        System.out.println("redirect===:" + name);
       // model.addAttribute("id",id);
        //model.addAttribute("name",name);// request.setAttribute(k,v)
        //return "redirect:http://localhost:8081/redirect2";

/*        String encode = null;
        try {//E6%2589%258B%25E6%259C%25
            encode = URLEncoder.encode(name, "utf-8");//手机

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/

        //重定向携带参数的形参对象
        redirectAttributes.addAttribute("id",id);
        redirectAttributes.addAttribute("name",name);

        return "redirect:/redirect2";
    }

    /**
     * 辅助测试
     * redirectTest2(Integer id,String name)
     *     String name : 底层：
     *       String name = req.getParamter(name); 由SpringMvc完成
     *                                ////E6%2589%258B%25E6%259C%25
     *               --- getParamter： URLDecoder.decode("encode","utf-8");手机
     *
     * @param id
     * @param name
     * @return
     */
    @GetMapping("/redirect2")
    public String redirectTest2(Integer id,String name){

        System.out.println("redirect2===:" + id);
        System.out.println("redirect2===:" + name);

        return "hello";
    }

    /**
     * 内部转发
     *    Servlet ----> Servlet
     *    Servlet ----> Jsp
     *
     */
    @GetMapping("/forward")
    public void forwardTest1(HttpServletRequest request){
       // request.getRequestDispatcher("/xixi").forward(request,re);
    }
    /**
     * SpringMvc 写法 内部转发
     */
    @GetMapping("/forward2")
    public String forwardTest2(){
        //转发到另一个Servlet方法
        return "forward:/xixi";
    }
    /**
     * 辅助方法
     * @return
     */
    @GetMapping("/xixi")
    public String forwardTest3(){
        return "hello";
    }
}
